package com.example.cemenghuii.controller;

import com.example.cemenghuii.dto.ApiResponse;
import com.example.cemenghuii.entity.News;
import com.example.cemenghuii.entity.User;
import com.example.cemenghuii.service.NewsService;
import com.example.cemenghuii.service.UserService;
import com.example.cemenghuii.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/news")
@CrossOrigin(origins = "*")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 创建新闻
     */
    @PostMapping
    public ApiResponse<Void> createNews(@RequestHeader("Authorization") String token,
                                        @RequestBody News news) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            User user = userService.getUserById(userId);
            if (user == null) {
                return ApiResponse.unauthorized("用户不存在");
            }

            news.setPublisherId(userId);
            news.setPublisherName(user.getUsername());

            boolean success = newsService.createNews(news);
            if (success) {
                if (userType == 2) {
                    return ApiResponse.success("新闻发布成功");
                } else {
                    return ApiResponse.success("新闻提交成功，等待审核");
                }
            } else {
                return ApiResponse.error("新闻创建失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 更新新闻
     */
    @PutMapping("/{id}")
    public ApiResponse<Void> updateNews(@RequestHeader("Authorization") String token,
                                        @PathVariable Long id,
                                        @RequestBody News news) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            // 检查权限
            if (!newsService.checkNewsPermission(id, userId, userType)) {
                return ApiResponse.forbidden("无权限操作此新闻");
            }

            news.setId(id);
            // 企业用户修改后需要重新审核
            if (userType == 1) {
                news.setStatus(0); // 重新设为待审核
            }

            boolean success = newsService.updateNews(news);
            if (success) {
                return ApiResponse.success("新闻更新成功");
            } else {
                return ApiResponse.error("新闻更新失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 删除新闻
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteNews(@RequestHeader("Authorization") String token,
                                        @PathVariable Long id) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            // 检查权限
            if (!newsService.checkNewsPermission(id, userId, userType)) {
                return ApiResponse.forbidden("无权限操作此新闻");
            }

            boolean success = newsService.deleteNews(id);
            if (success) {
                return ApiResponse.success("新闻删除成功");
            } else {
                return ApiResponse.error("新闻删除失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取新闻详情
     */
    @GetMapping("/{id}")
    public ApiResponse<News> getNewsDetail(@PathVariable Long id,
                                           @RequestParam(defaultValue = "true") Boolean incrementView) {
        try {
            News news = newsService.getNewsDetail(id, incrementView);
            if (news == null) {
                return ApiResponse.notFound("新闻不存在");
            }
            return ApiResponse.success(news);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取新闻列表
     */
    @GetMapping("/list")
    public ApiResponse<Map<String, Object>> getNewsList(@RequestHeader("Authorization") String token,
                                                        @RequestParam(required = false) String title,
                                                        @RequestParam(required = false) String author,
                                                        @RequestParam(required = false) Integer status,
                                                        @RequestParam(defaultValue = "1") Integer page,
                                                        @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            Long publisherId = null;
            // 企业用户只能查看自己的新闻
            if (userType == 1) {
                publisherId = userId;
            }

            Map<String, Object> result = newsService.getNewsList(title, author, status, publisherId, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取我的新闻列表
     */
    @GetMapping("/my")
    public ApiResponse<Map<String, Object>> getMyNewsList(@RequestHeader("Authorization") String token,
                                                          @RequestParam(defaultValue = "1") Integer page,
                                                          @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            Map<String, Object> result = newsService.getNewsByPublisherId(userId, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 审核新闻（管理员功能）
     */
    @PutMapping("/{id}/audit")
    public ApiResponse<Void> auditNews(@RequestHeader("Authorization") String token,
                                       @PathVariable Long id,
                                       @RequestBody Map<String, Integer> auditData) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            Integer status = auditData.get("status");
            boolean success = newsService.auditNews(id, status);
            if (success) {
                String message = status == 1 ? "审核通过" : "审核拒绝";
                return ApiResponse.success(message);
            } else {
                return ApiResponse.error("审核失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取待审核新闻列表（管理员功能）
     */
    @GetMapping("/pending")
    public ApiResponse<Map<String, Object>> getPendingNewsList(@RequestHeader("Authorization") String token,
                                                               @RequestParam(defaultValue = "1") Integer page,
                                                               @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            Map<String, Object> result = newsService.getPendingNewsList(page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取已发布新闻列表（小程序端）
     */
    @GetMapping("/published")
    public ApiResponse<Map<String, Object>> getPublishedNewsList(@RequestParam(required = false) String keyword,
                                                                 @RequestParam(defaultValue = "1") Integer page,
                                                                 @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = newsService.getPublishedNewsList(keyword, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}